<?php
/*
@author: wjf
@contact: Hurrican
@software: PhpStorm
@create: 2022/8/18 15:28
*/
declare(strict_types=1);
namespace app\api\service\applets;

use app\common\library\helper;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Log;
use think\helper\Str;

class Base{
    private static string $mini_token_key = 'baize_token_key';
    private static int $expire_time = 1800;
    const TemplateId_Arr = [
        'RUN_TWICE_REWARD' => 'phjyeTBlskcgQDClOXuHt1Vmjmb96C5n68Cfi9-SFvE',
        'RUN_LOTTERY_REWARD' => 'dV_jWuYHgjlDYkoC5fX2Sc4cHm1OsXip67PQJ73KzWw'
    ];

    private $app_id;
    private $app_secret;
    public function __construct()
    {
        $config_detail = Config::get('wechat');
        $this->app_id = $config_detail['mini_program']['baize']['app_id'];
        $this->app_secret = $config_detail['mini_program']['baize']['app_secret'];
    }


    //获取access_token
    public function getAccessToken():string
    {
        $access_token = Cache::store('redis')->get(self::$mini_token_key);
        if(!$access_token){
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->app_id.'&secret='.$this->app_secret;
            $data = json_decode(curl_get_https($url), true);
            $access_token = $data['access_token'] ?? '';
            if(!$access_token){
                throwError('获取token异常,请检查');
            }
            Cache::store('redis')->set(self::$mini_token_key,$access_token,self::$expire_time);
        }
        return $access_token;
    }


    //发送开奖消息--二级奖池
    public function sendTwiceRewardRunLotteryMessage($data,$jump_url,$access_token = ''): bool
    {
        try {
            $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$this->getAccessToken();
            $template_data = [
                'thing1' => [
                    'value' => $data['activity_name'].'开奖啦',
                ],
                'thing5' => [
                    'value' => $data['is_win'] == 1 ? '您中奖啦' : '您未中奖',
                ]
            ];
            $params = [
                'touser' => $data['open_id'] ?? 'oZOb75LsUl36m_aSBjPhOWAi2Vyg',
                'template_id' => self::TemplateId_Arr['RUN_TWICE_REWARD'],
                'page' => $jump_url,
                'miniprogram_state' => 'developer',
                'lang' => 'zh_CN',
                'data' => $template_data
            ];
            $post_data = json_encode($params);
            $result = curl_post_https($url,$post_data);
            Log::channel('queue')->info($data['open_id'].'发送开奖消息结果：'.$result);
            $result = json_decode($result,true);
            if($result['errcode'] != 0){
                if($result['errcode'] == 40001){
                    //重新获取access_token 请求
                    Cache::store('redis')->delete(self::$mini_token_key);
                    $this->sendTwiceRewardRunLotteryMessage($data,$jump_url,self::getAccessToken());
                }
            }
            return true;
        }catch (\Exception $e){
            Log::channel('queue')->info('订阅消息异常：'.$e->getMessage());
            return false;
        }

    }



    //发送中签消息--抽选
    public function sendLotteryWinCodeMessage($data,$access_token = ''): bool
    {
        try {
            $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$this->getAccessToken();
            $template_data = [
                'thing1' => [
                    'value' => $data['goods_name'], //抽签商品
                ],
                'thing2' => [
                    'value' => $data['is_win'] == 1 ? '已中签' : '未中签',
                ],
                'thing3' => [
                    'value' => '详情请在限时抽选页面获取',
                ]
            ];
            $params = [
                'touser' => $data['open_id'] ?? 'oZOb75LsUl36m_aSBjPhOWAi2Vyg',
                'template_id' => self::TemplateId_Arr['RUN_LOTTERY_REWARD'],
                'page' => 'pages/shopRelation/activity/drawNum?id='.$data['activity_id'],
                'miniprogram_state' => 'developer',
                'lang' => 'zh_CN',
                'data' => $template_data
            ];
            $post_data = json_encode($params);
            $result = curl_post_https($url,$post_data);
            Log::channel('message')->info($data['open_id'].'#'.$result);
            return true;
        }catch (\Exception $e){
            Log::channel('message')->info($e->getMessage());
            return false;
        }

    }







}
